// 添加商品
import React, { useEffect, useState } from 'react';
import { Input, Select, Space, Checkbox, Button, Form, Collapse, Table, Tabs, Cascader, Image, message, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import type { TabsProps } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import '../../css/operation.css'
import { getAddShop, addShop, getAddTag, getLevel, getBrand } from '../../../api/opreationApi'

// 表格
interface DataType {
  key: React.Key;
  goodsId: number;
  brandName: string;//品牌
  categoryName: string;//分类
  goodsName: string;//商品名称
  goodsSerNum: string;//货号
  goodsPriceRange: string;//价格
  skuImag: string;//图片
  goodsSell: string;//销量
}


// 联级选择
interface Option {
  value: string;
  label: string;
  children?: Option[];
}


export default function OperationSlide() {
  const [shopData, setShopData] = useState<DataType[]>([])//当前页渲染数据
  const [pageSize, setPageSize] = useState<number>(7) //每页条数
  const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
  const [total, setTotal] = useState<number>()//总条数
  const [sortWay, setSortWay] = useState<string>()//选择排序方式
  const [labels, setLabels] = useState<any>()//标签数据
  const [options, setOptions] = useState<any>()//分类下拉数据
  const [tsaId, setTsaId] = useState<any>()//专区id
  const [brand, setBrand] = useState<any>()//品牌下拉数据
  const [searchKeyWord, setSearchKeyWord] = useState<string>()//查询关键字
  const [searchBrand, setSearchBrand] = useState<string>()//查询品牌
  const [searchType, setSearchType] = useState<string>()//查询类型


  const getData = () => {
    setTsaId(Number(sessionStorage.getItem('tsaId')))
    getAddShop({
      currentPage, pageSize, sortWay, tsaId, keyWord: searchKeyWord, brand: searchBrand, type: searchType
    }).then(res => {
      setShopData(res.data.vyyGoods)
      setTotal(res.data.total)
    })
  }
  useEffect(() => {
    getData()
  }, [currentPage, pageSize, sortWay, tsaId, searchKeyWord, searchBrand, searchType])

  //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
  const pageChange = (page: number, pageSize: number) => {
    setPageSize(pageSize)
    setCurrentPage(page)
  }

  // 标签请求
  useEffect(() => {
    getAddTag().then(res => {
      const labels = res.data.map((item:any) => ({
        label: item.labelName, value: item.labelName
      }))
      setLabels(labels)
    })
  }, [])

  // 查询分级信息
  useEffect(() => {
    getLevel().then(res => {
      function generateTree(res: any) {
        return res.reduce((prev: any, curr: any) => {
          const item = {
            value: curr.name,
            label: curr.name,
            children: curr.children ? generateTree(curr.children) : undefined
          }
          prev.push(item)
          return prev
        }, [])
      }
      const result = generateTree(res.data)
      setOptions(result)
    })
  }, [])

  // 查询品牌
  useEffect(() => {
    getBrand().then(res => {
      const arrBrand = res.data.map((item:any) => ({
        value: item,
        label: item
      }))
      setBrand(arrBrand)
    })
  }, [])

  const { Panel } = Collapse;
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);  // 表格选中对应条数的id
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  }; //选中后改变选中内容
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
    },
    {
      title: '商品图片',
      dataIndex: 'skuImag',
      render: (_, record) => (
        <Image
          width={50}
          height={50}
          src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsSerNum',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
    },
    {
      title: '销量',
      dataIndex: 'goodsSell',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button className='add' onClick={() => add(record)}>添加</Button>
        </Space >
      ),
    },
  ];//表格的行列


  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };//表格多选逻辑
  const [form] = Form.useForm();//使用From表单，用于默认值


  // 操作部分
  // （1）单个商品添加
  const add = (value: any) => {
    message.success('已添加到指定专区！')
    const tsaId = sessionStorage.getItem('tsaId')
    const goodsId = value.goodsId
    addShop({ tsaId, goodsId })
  }


  // (2)查询
  const sreach = (values: any) => {
    setSearchKeyWord(values.keyword)
    setSearchBrand(values.brand)
    setSearchType(values.type.length === 1 ? (values.type[0]) : values.type.length === 2 ? (values.type[1]) : values.type.length === 3 ? (values.type[2]) : values.type)
  }

  // (3)重置
  const reset = () => {
    form.resetFields()
    getAddShop({
      currentPage, pageSize, tsaId
    }).then(res => {
      setShopData(res.data.vyyGoods)
      setTotal(res.data.total)
      message.success('重置成功！')
    })
  }
  // 排序
  const onChange = (key: string) => {
    setSortWay(key)
  };

  // 排序
  const handleChangeSort = (values: string) => {
    setSortWay(values)
  }
  // 排序列表
  const items: TabsProps['items'] = [
    {
      key: '按销量顺序',
      label: `按销量顺序`,
    },
    {
      key: '按销量倒序',
      label: `按销量倒序`,
    },
  ];
  return (<div>
    {/* 头部标题 */}
    <p className='head'>添加商品</p>
    {/* 搜索操作 */}
    <Collapse className='collapse' defaultActiveKey={['1']}>
      <Panel header="筛选查询" key="1">
        <div className='operate-wrap operate-left' id='operate-wrap'>
          {/* 搜索关键词 */}
          <Form form={form} className='operate-left' onFinish={sreach}>
            <Form.Item label="关键词：" className='operate-left-item' name='keyword'>
              <Input placeholder=" 商品名称/商品货号" className='search' />
            </Form.Item>
            {/* 商品分类 */}
            <Form.Item label='分类' className='operate-left-item' name='type'>
              <Cascader placeholder="请选择类型" options={options} changeOnSelect />
            </Form.Item>
            {/* 商品品牌 */}
            <Form.Item label='品牌' className='operate-left-item' name='brand'>
              <Select
                style={{ width: 120 }}
                allowClear
                options={brand}
                className='drop'
                placeholder='请选择品牌'
              />
            </Form.Item>
            {/* 操作 */}
            <Form.Item>
              <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
              <Button className='reset operate-left-item' onClick={reset}>重置</Button>
            </Form.Item>
          </Form>
        </div>
      </Panel>
    </Collapse>

    {/* 商品排序 */}
    <div className='shopSort bottom'>
      <p className='bottomLabel'>商品排序</p>
      <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
    </div>
    {/* 标签选择 */}
    <div className='shopSort bottom'>
      <p>标签筛选</p>
      <Checkbox.Group options={labels} defaultValue={['Pear']} />
    </div>
    {/* 表格列表整体 */}
    <div className='table'>
      {/* 表格操作 */}
      <div className='operationTable'>
        {/* 排序 */}
        <Form>
          <Form.Item label='排序：' name='state'>
            <Select
              placeholder="请选择排序"
              onChange={handleChangeSort}
              style={{ width: 120 }}
              allowClear
              options={[{ value: '按销量顺序', label: '按销量顺序' }, { value: '按销量倒序', label: '按销量倒序' }]}
              className='drop'
            />
          </Form.Item>
        </Form>
      </div>
      {/* 表格 */}
      <ConfigProvider locale={zh_CN}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={shopData}
          rowKey={item => item.goodsId}
          pagination={{
            position: ['bottomRight'],
            defaultPageSize: 5,
            pageSizeOptions: [2, 3, 5, 6],
            showQuickJumper: true,
            showSizeChanger: true,
            total: total,
            onChange: pageChange,
            pageSize: pageSize,
            showTotal: (total: number) => (`共有 ${total} 条数据`)
          }} />
      </ConfigProvider>
    </div>
  </div >)
}
